class WechatsController < ApplicationController
  wechat_responder

  on :text do |request, content|
    request.reply.text "echo: #{content}" #Just echo
  end

  on :text, with: '我是谁' do |request|
    if require_bind! request
      user = binded_user request
      request.reply.text "#{user.name || user.email}" #Just echo
    else
      require_bind_msg(request)
    end
  end

  on :event, with: 'subscribe' do |request|
    request.reply.text '感谢关注'
  end

  # 绑定账户, key: bind_account
  on :event, with: 'bind_account' do |request, content|
    if require_bind!(request)
      request.reply.text "已经绑定，点击链接直接登陆 http://#{Settings.host}/account/login_by_wechat?oid=#{request[:FromUserName]}"
    else
      request.reply.text "点击链接绑定 http://#{Settings.host}/account/bind?oid=#{request[:FromUserName]}"
    end
  end

  on :event, with: 'my_reward' do |request|
    if require_bind! request
      user = binded_user(request)
      request.reply.text compile_month_reward(user)
    else
      require_bind_msg(request)
    end
  end

  # catch view event
  on :event do |request|
  end

  on :fallback, respond: "工程师Coding中，敬请期待"

  # helper methods
  class << self
    def require_bind!(request)
      if is_bind?(request)
        true
      else
        false
      end
    end

    def require_bind_msg(request)
      request.reply.text "还未绑定账户，请点击链接绑定 http://#{Settings.host}/account/bind?oid=#{request[:FromUserName]}"
    end

    def is_bind?(request)
      binded_user(request).present?
    end

    def binded_user(request)
      openid = request[:FromUserName]
      User.where(wechat_openid: openid).first
    end

    def compile_month_reward(user)
      current_month = Date.current
      previous_month = Date.current.prev_month

      previous_month_reward = Sale.staff_month_reward(user.id, previous_month)
      current_month_reward = Sale.staff_month_reward(user.id, current_month)

      template = SiteConfig.wechat_month_reward.value
      msg = template.gsub("\r", '')
                    .gsub('#name#', user.name_or_email)
                    .gsub('#previous_month#', previous_month.strftime('%Y-%m'))
                    .gsub('#previous_month_reward#', previous_month_reward.to_s)
                    .gsub('#current_month#', current_month.strftime('%Y-%m'))
                    .gsub('#current_month_reward#', current_month_reward.to_s)
      msg
    end
  end
end
